import xml.etree.ElementTree as ET
import time
from datetime import datetime

class XMLBuilder:
    @staticmethod
    def catalog_response(device_id, channel_id, local_ip, sn=None):
        # 如果没有提供SN，则生成一个
        if sn is None:
            sn = str(int(time.time()))
            
        root = ET.Element("Response")
        ET.SubElement(root, "CmdType").text = "Catalog"
        ET.SubElement(root, "SN").text = sn
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "SumNum").text = "1"
        
        device_list = ET.SubElement(root, "DeviceList", Num="1")
        item = ET.SubElement(device_list, "Item")
        
        # 通道基本信息 - 严格按照GB28181标准
        ET.SubElement(item, "DeviceID").text = channel_id
        ET.SubElement(item, "Name").text = "Main Camera Channel"
        ET.SubElement(item, "Manufacturer").text = "MyCompany"
        ET.SubElement(item, "Model").text = "IPCamera Pro"
        ET.SubElement(item, "Owner").text = "Owner"
        ET.SubElement(item, "CivilCode").text = "4101050000"  # 使用正确的域编码
        ET.SubElement(item, "Address").text = local_ip
        ET.SubElement(item, "Parental").text = "0"
        ET.SubElement(item, "ParentID").text = device_id
        ET.SubElement(item, "RegisterWay").text = "1"
        ET.SubElement(item, "Secrecy").text = "0"
        ET.SubElement(item, "Status").text = "ON"
        
        # 网络信息
        ET.SubElement(item, "IPAddress").text = local_ip
        ET.SubElement(item, "Port").text = "5060"
        
        # 设备能力信息
        ET.SubElement(item, "PTZType").text = "1"  # 支持PTZ
        ET.SubElement(item, "Position").text = "1"  # 安装位置
        ET.SubElement(item, "RoomType").text = "1"  # 房间类型
        ET.SubElement(item, "UseType").text = "1"   # 使用类型
        ET.SubElement(item, "SupplyLightType").text = "1"  # 补光类型
        ET.SubElement(item, "DirectionType").text = "1"    # 方向类型
        ET.SubElement(item, "Resolution").text = "3"       # 分辨率能力级别
        
        # 新增必要字段
        ET.SubElement(item, "Longitude").text = "0"     # 经度
        ET.SubElement(item, "Latitude").text = "0"      # 纬度
        ET.SubElement(item, "Info").text = "Camera"     # 设备信息
        
        return ET.tostring(root, encoding='utf-8').decode()

    @staticmethod
    def keepalive(device_id):
        root = ET.Element("Notify")
        ET.SubElement(root, "CmdType").text = "Keepalive"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "Status").text = "OK"
        ET.SubElement(root, "Info").text = "KeepAlive"
        return ET.tostring(root, encoding='utf-8').decode()
    
    @staticmethod
    def device_info_response(device_id, device_info):
        """构建设备信息响应"""
        root = ET.Element("Response")
        ET.SubElement(root, "CmdType").text = "DeviceInfo"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "DeviceName").text = device_info["name"]
        ET.SubElement(root, "Manufacturer").text = device_info["manufacturer"]
        ET.SubElement(root, "Model").text = device_info["model"]
        ET.SubElement(root, "Firmware").text = device_info["firmware"]
        ET.SubElement(root, "Channel").text = str(len(device_info["channels"]))
        return ET.tostring(root, encoding='utf-8').decode()
    
    @staticmethod
    def playback_response(device_id, records):
        """构建回放记录响应"""
        root = ET.Element("Response")
        ET.SubElement(root, "CmdType").text = "RecordInfo"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "Name").text = "RecordList"
        ET.SubElement(root, "SumNum").text = str(len(records))
        
        record_list = ET.SubElement(root, "RecordList")
        for record in records:
            item = ET.SubElement(record_list, "Item")
            ET.SubElement(item, "DeviceID").text = device_id
            ET.SubElement(item, "Name").text = record["name"]
            ET.SubElement(item, "FilePath").text = record["path"]
            ET.SubElement(item, "Address").text = record["address"]
            ET.SubElement(item, "StartTime").text = record["start"]
            ET.SubElement(item, "EndTime").text = record["end"]
            ET.SubElement(item, "Secrecy").text = "0"
            ET.SubElement(item, "Type").text = "time"
        
        return ET.tostring(root, encoding='utf-8').decode()
    
    @staticmethod
    def ptz_response(device_id, result_code):
        """PTZ控制响应"""
        root = ET.Element("Response")
        ET.SubElement(root, "CmdType").text = "DeviceControl"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "Result").text = result_code
        return ET.tostring(root, encoding='utf-8').decode()
    
    @staticmethod
    def alarm_notify(device_id, alarm_type, description):
        """报警通知"""
        root = ET.Element("Notify")
        ET.SubElement(root, "CmdType").text = "Alarm"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        
        info = ET.SubElement(root, "Info")
        ET.SubElement(info, "AlarmPriority").text = "1"
        ET.SubElement(info, "AlarmMethod").text = "1"
        ET.SubElement(info, "AlarmTime").text = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        ET.SubElement(info, "AlarmDescription").text = description
        ET.SubElement(info, "Longitude").text = "0.0"
        ET.SubElement(info, "Latitude").text = "0.0"
        
        items = ET.SubElement(info, "Info")
        item = ET.SubElement(items, "Item")
        ET.SubElement(item, "AlarmType").text = str(alarm_type)
        
        return ET.tostring(root, encoding='utf-8').decode()

    @staticmethod
    def device_status_response(device_id):
        """设备状态响应"""
        root = ET.Element("Response")
        ET.SubElement(root, "CmdType").text = "DeviceStatus"
        ET.SubElement(root, "SN").text = str(int(time.time()))
        ET.SubElement(root, "DeviceID").text = device_id
        ET.SubElement(root, "Result").text = "OK"
        ET.SubElement(root, "Online").text = "ONLINE"
        ET.SubElement(root, "Status").text = "OK"
        ET.SubElement(root, "Reason").text = "正常"
        ET.SubElement(root, "Encode").text = "ON"
        ET.SubElement(root, "Record").text = "OFF"
        ET.SubElement(root, "DeviceTime").text = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        return ET.tostring(root, encoding='utf-8').decode()